<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'a.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="<c:url value='/ajax/ajaxutils.js'/>"></script>
	<script type="text/javascript">
		window.onload = function() {
			var province = document.getElementById("province");
			ajax(
				{
					url: "<c:url value='/demo8/ProvinceServlet'/>",
					type: "json",
					callback: function(data) {
						for ( var i = 0; i < data.length; i++) {
							var op = document.createElement("option");
							var textNode = document.createTextNode(data[i].name);
							op.append(textNode);
							op.value = data[i].pid;
							province.appendChild(op);
						}
					}
				}		
			);
			var city = document.getElementById("city");
			province.onchange = function() {
				ajax(
					{
						url: "<c:url value='/demo8/CityServlet'/>",
						method: "POST",
						type: "json",
						params: "pid=" + province.value,
						callback: function(data) {
							// 删除除了“请选择”以外的option
							var opts = city.getElementsByTagName("option");
							while (opts.length > 1) {
								city.removeChild(opts[1]);
							}
							
							for ( var i = 0; i < data.length; i++) {
								var cityName = data[i].name;								
								var op = document.createElement("option");
								var textNode = document.createTextNode(cityName);
								op.append(textNode);
								op.value = cityName;
								city.appendChild(op);
							}
						}
					}		
				);
			};
		};
	</script>
  </head>
  
  <body>
	<h1>AJAX 省市联动 MySQL</h1>
	<select name="province" id="province">
		<option>==请选择省份==</option>
	</select>
	<select name="city" id="city">
		<option>==请选择城市==</option>
	</select>
  </body>
</html>
